package com.studentmanage.manage_user.service;

import com.studentmanage.framework.domain.common.response.CommonCode;
import com.studentmanage.framework.domain.common.response.ResponseResult;
import com.studentmanage.framework.domain.common.response.ResponseValue;
import com.studentmanage.framework.domain.system.LoginResult;
import com.studentmanage.framework.domain.system.User;
import com.studentmanage.framework.utils.ExportSql;
import com.studentmanage.manage_user.dao.UserMapper;
import com.studentmanage.manage_user.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired(required = false)
    private UserMapper userMapper;

    //登录
    public LoginResult login(User user, String ipAdress) {
        User one = userRepository.findByUserName(user.getUserName());
        if (one == null) {
            return new LoginResult("error");
        }
        if (!one.getPassword().equals(user.getPassword())) {
            return new LoginResult("error");
        }
        one.setIp(ipAdress);
        one.setLastTime(one.getTime());
        one.setTime(new Date());
        userRepository.save(one);
        return new LoginResult(one.getToken());
    }

    //获取用户列表
    public List<User> getList() {
        return userRepository.findAll();
    }

    //删除用户
    public ResponseResult delete(String id) {
        Optional<User> optional = userRepository.findById(id);
        if (!optional.isPresent()) {
            return new ResponseResult(CommonCode.FAIL);
        }
        userRepository.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //增加用户
    public ResponseResult add(User user) {
        User one = userRepository.findByUserName(user.getUserName());
        if (one == null) {
            user.setDelTag("0");
            userRepository.save(user);
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    //修改用户
    public ResponseResult update(User user) {
        if (user == null) {
            return new ResponseResult(CommonCode.FAIL);
        }
        userRepository.save(user);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //查询用户
    public ResponseValue<User> queryUser(String name) {
        if (StringUtils.isEmpty(name)) {
            return new ResponseValue<User>(false, null);
        }
        User user = userRepository.findByUserName(name);
        if (user == null) {
            return new ResponseValue<User>(false, null);
        }
        return new ResponseValue<User>(true, user);

    }

    //下载sql文件
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        File delFile = new File("F:\\sql\\student_manage.sql");
        delFile.delete();
        ExportSql.exportSql();
        try {
            Thread.currentThread().sleep(3000);//毫秒
        } catch (Exception e) {
        }
        File file = new File("F:\\sql\\student_manage.sql");
        // 如果文件名存在，则进行下载
        if (file.exists()) {

            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("student_manage.sql", "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                file.delete();
            }
        }
        return null;
    }
}
